package com.huanglejing.shanggou.activity

import android.graphics.Color
import android.os.Bundle
import android.support.v4.util.ArrayMap
import android.support.v7.widget.GridLayoutManager
import android.view.View
import android.widget.TextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseQuickAdapter.*
import com.chad.library.adapter.base.BaseViewHolder
import com.huanglejing.mylibrary.KLog
import com.huanglejing.shanggou.R
import com.huanglejing.shanggou.adapter.BaseComeAdapter
import com.huanglejing.shanggou.bean.NewComeProBean
import com.huanglejing.shanggou.common.AppBaseActivity
import com.huanglejing.shanggou.common.AppContext
import com.huanglejing.shanggou.data.CacheCustomerId
import com.huanglejing.shanggou.data.beanDao
import com.huanglejing.shanggou.data.getCacheGoods
import com.huanglejing.shanggou.greendao.CacheGoodsBean
import com.huanglejing.shanggou.greendao.CacheGoodsBeanDao
import com.huanglejing.shanggou.interfaces.RecomendProContract.RecomendProPresenter
import com.huanglejing.shanggou.interfaces.RecomendProContract.RecomendProView
import com.huanglejing.shanggou.presenterimpl.RecomendProImpl
import com.huanglejing.shanggou.view.EmptyLayout
import kotlinx.android.synthetic.main.activity_recomend_pro.*
import kotlinx.android.synthetic.main.layout_product_list_item.*
import rx.Observable
import java.util.*

class RecomendProActivity : AppBaseActivity<RecomendProPresenter<RecomendProView>, RecomendProView>(), RecomendProView {
    private var mData: ArrayList<NewComeProBean>? = arrayListOf()
    private var mNextAdapter: BaseComeAdapter? = null
    protected var mEmptyLayout: EmptyLayout? = null
    private val random = Random()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initWidget();
    }


    private fun initWidget() {
        setAPPTitle(resources.getString(R.string.str_recommend))
        val manager = GridLayoutManager(this@RecomendProActivity, 2)
        xr_toolbar_list?.setLayoutManager(manager)
        mNextAdapter = BaseComeAdapter(mData ?: arrayListOf())

        xr_toolbar_list?.setAdapter(mNextAdapter)

        var loadAll = getCacheGoods()?.filter {
            it.companyId?.equals(AppContext.get().companyId ?: "") ?: false
        }
        mNextAdapter?.setCacheData(loadAll)
        mNextAdapter?.setOnItemClickListener(object : BaseComeAdapter.OnItemClickListener {
            override fun onItemClick(v: View?, position: Int) {

            }
        })
        mNextAdapter?.setCacheOrderBeanListener(object : BaseComeAdapter.CacheOrderBeanListener {
            override fun onCacheOrderBeanAdd(position: Int, selectNum: Int, bean: NewComeProBean?) {
                var loadAll = getCacheGoods()?.filter {
                    it.companyId?.equals(AppContext.get().companyId ?: "") ?: false
                }
                var isUpdate = false
                var updateBean: CacheGoodsBean? = null
                loadAll?.forEachIndexed { index, orderBean ->
                    if (orderBean?.goodNO?.equals(bean?.id ?: "") ?: false) {
                        isUpdate = true
                        updateBean = orderBean
                    }
                }
                if (isUpdate && updateBean != null) {
                    updateBean?.goodNO = bean?.id ?: ""
                    updateBean?.companyId = AppContext.get()?.companyId ?: ""
                    updateBean?.customerId = CacheCustomerId ?: ""
                    updateBean?.bz = updateBean?.bz ?: ""
                    updateBean?.categoryGUID = ""
                    updateBean?.num = selectNum?.div(bean?.bagCount?.toIntOrNull()?:1)?.toString()?:"0"
                    updateBean?.price = bean?.price ?: ""
                    updateBean?.bagCount = bean?.bagCount ?: ""
                    updateBean?.boxCount = bean?.boxCount ?: ""
                    updateBean?.count = bean?.count ?: ""
                    updateBean?.name = bean?.name ?: ""
                    updateBean?.no = bean?.no ?: ""
                    updateBean?.parentGuid = bean?.parentGuid ?: ""
                    updateBean?.url = bean?.url ?: ""
                    updateBean?.xname = bean?.xname ?: ""
                    updateBean?.zk = bean?.zk ?: ""
                    val zhekou = bean?.zk?.toDoubleOrNull()?.div(100) ?: 0.00
                    updateBean?.totalPrice = bean?.price?.toDoubleOrNull()?.times(selectNum)?.times(1.minus(zhekou))?.toString() ?: ""
                    beanDao?.update(updateBean)
                } else if (!isUpdate && updateBean == null) {
                    updateBean = CacheGoodsBean()
                    updateBean?.goodNO = bean?.id ?: ""
                    updateBean?.companyId = AppContext.get()?.companyId ?: ""
                    updateBean?.customerId = CacheCustomerId ?: ""
                    updateBean?.bz = ""
                    updateBean?.categoryGUID = ""
                    updateBean?.num = selectNum?.div(bean?.bagCount?.toIntOrNull()?:1)?.toString()?:"0"
                    updateBean?.price = bean?.price ?: ""
                    updateBean?.bagCount = bean?.bagCount ?: ""
                    updateBean?.boxCount = bean?.boxCount ?: ""
                    updateBean?.count = bean?.count ?: ""
                    updateBean?.name = bean?.name ?: ""
                    updateBean?.no = bean?.no ?: ""
                    updateBean?.parentGuid = bean?.parentGuid ?: ""
                    updateBean?.url = bean?.url ?: ""
                    updateBean?.xname = bean?.xname ?: ""
                    updateBean?.zk = bean?.zk ?: ""
                    val zhekou = bean?.zk?.toDoubleOrNull()?.div(100) ?: 0.00
                    updateBean?.totalPrice = bean?.price?.toDoubleOrNull()?.times(selectNum)?.times(1.minus(zhekou))?.toString() ?: ""
                    beanDao?.insert(updateBean)
                }

            }

            override fun onCacheOrderBeanMinius(position: Int, selectNum: Int, bean: NewComeProBean?) {
                var loadAll = getCacheGoods()?.filter {
                    it.companyId?.equals(AppContext.get().companyId ?: "") ?: false
                }
                var isUpdate = false
                var updateBean: CacheGoodsBean? = null
                loadAll?.forEachIndexed { index, orderBean ->
                    if (orderBean?.goodNO?.equals(bean?.id ?: "") ?: false) {
                        isUpdate = true
                        updateBean = orderBean
                    }
                }
                if (isUpdate && updateBean != null && selectNum > 0) {
                    updateBean?.goodNO = bean?.id ?: ""
                    updateBean?.companyId = AppContext.get()?.companyId ?: ""
                    updateBean?.customerId = CacheCustomerId ?: ""
                    updateBean?.bz = updateBean?.bz ?: ""
                    updateBean?.categoryGUID = ""
                    updateBean?.num = selectNum?.div(bean?.bagCount?.toIntOrNull()?:1)?.toString()?:"0"
                    updateBean?.price = bean?.price ?: ""
                    updateBean?.bagCount = bean?.bagCount ?: ""
                    updateBean?.boxCount = bean?.boxCount ?: ""
                    updateBean?.count = bean?.count ?: ""
                    updateBean?.name = bean?.name ?: ""
                    updateBean?.no = bean?.no ?: ""
                    updateBean?.parentGuid = bean?.parentGuid ?: ""
                    updateBean?.url = bean?.url ?: ""
                    updateBean?.xname = bean?.xname ?: ""
                    updateBean?.zk = bean?.zk ?: ""
                    updateBean?.totalPrice = bean?.price?.toDoubleOrNull()?.times(selectNum)?.toString() ?: ""
                    beanDao?.update(updateBean)
                } else if (isUpdate && updateBean != null && selectNum == 0) {
                    beanDao?.delete(updateBean)
                }

            }
        })
        manager.spanSizeLookup =
                object : GridLayoutManager.SpanSizeLookup() {
                    override fun getSpanSize(position: Int): Int {
                        var itemViewType = mNextAdapter?.getItemViewType(position)
                        if (itemViewType == HEADER_VIEW || itemViewType == EMPTY_VIEW || itemViewType == FOOTER_VIEW) {
                            return 2
                        } else {
                            return 1
                        }

                    }
                }
        initEmptyView()
    }

    fun loadComplete(end: Boolean = false) {
        mNextAdapter?.setHeaderAndEmpty(mNextAdapter?.headerLayoutCount ?: 0 > 0)
      //  xr_toolbar_list.post {
            mNextAdapter?.loadMoreComplete()
            if (end) {
                mNextAdapter?.loadMoreEnd()
                if (mNextAdapter?.data?.size ?: 0 <= 0) {
                    mEmptyLayout?.setErrorType(EmptyLayout.NODATA)
                    mNextAdapter?.setEmptyView(mEmptyLayout)
                } else {
                    val foot = EmptyLayout.getEmptyLayout(EmptyLayout.COMPLETE, xr_toolbar_list)
                    mNextAdapter?.removeAllFooterView()
                    mNextAdapter?.setFooterView(foot)
                }
            }
      //  }
    }

    private fun initEmptyView() {
        this.mEmptyLayout = EmptyLayout.getEmptyLayout(EmptyLayout.NODATA, xr_toolbar_list)
//        mEmptyLayout?.setOnLayoutClickListener(View.OnClickListener { mBasePresenter.getRecomendProList() })
//        mEmptyLayout?.setTag(EmptyLayout::class.java.name)
//        if (mNextAdapter?.getEmptyView() == null)
//            mNextAdapter?.setEmptyView(mEmptyLayout)//空view;

    }

    override fun createPresenter(): RecomendProPresenter<RecomendProView> = RecomendProImpl()

    override fun getLayoutId(): Int = R.layout.activity_recomend_pro

    override fun requestPermission() {
    }

    override fun getRequestParams(): Observable<Map<String, Any>> {
        val map = ArrayMap<String, String>().apply {
            put("companyId", AppContext.get().companyId)
        }
        return Observable.just(map)
    }

    override fun <T> showContent(data: T?) {
        try {
            val mNetData = data as? ArrayList<NewComeProBean>
            if (mNetData != null && mData!=null) {
                mData?.clear()
                mData?.addAll(mNetData)
                mNextAdapter?.setNewData(mData ?: arrayListOf())

            }else{
                mNextAdapter?.setNewData(arrayListOf())
            }
            loadComplete(true)
        } catch (e: Exception) {
            KLog.e(e?.message)
        }

    }

    override fun showError(e: Throwable?) {
        KLog.e(e?.message)
        mNextAdapter?.setNewData(arrayListOf())
        mNextAdapter?.setHeaderAndEmpty(mNextAdapter?.headerLayoutCount ?: 0 > 0)
        mNextAdapter?.loadMoreComplete()
        mNextAdapter?.loadMoreEnd()
        mEmptyLayout?.setErrorType(EmptyLayout.NETWORK_ERROR)
        mEmptyLayout?.setOnLayoutClickListener {
            mBasePresenter?.getRecomendProList()
        }
        mNextAdapter?.setEmptyView(mEmptyLayout)
    }
}
